<template>
  <div class="system-user">
    <search-list ref="userList" :api-url="$url.SysUserList" :option="searchOpt" :itemPerRow="8">
      <el-table-column prop="id" label="ID" width="50"></el-table-column>
      <el-table-column prop="username" label="用户账号"></el-table-column>
      <el-table-column prop="nickname" label="用户昵称"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="enabled" label="账号状态">
        <template slot-scope="scope">
          <div>
            <el-switch
              :value="scope.row.enabled"
              active-color="#67C23A"
              active-text="启用"
              :active-value="1"
              inactive-color="#F56C6C"
              inactive-text="禁用"
              :inactive-value="0"
              @change="switchEnabled(scope.row)"
              :disabled="$userInfo.info.id === scope.row.id"
            ></el-switch>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="150px"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="primary"
            @click="check(scope.row)"
            icon="el-icon-edit"
            v-permission="['user:check']"
            :disabled="scope.row.username === 'admin'"
          ></el-button>
          <el-button
            type="danger"
            @click="del(scope.row)"
            v-permission="['user:del']"
            icon="el-icon-delete"
            :disabled="scope.row.username === 'admin'"
          ></el-button>
        </template>
      </el-table-column>

      <div class="btn-after" slot="btn-after">
        <el-button
          type="success"
          icon="el-icon-plus"
          @click="dialogShow = true"
          v-permission="['user:add']"
        >
          新增用户
        </el-button>
      </div>
    </search-list>

    <el-dialog
      :title="dialogInfo.id ? `修改用户` : `新增用户`"
      :visible="dialogShow"
      :show-close="false"
      width="500px"
    >
      <el-form
        label-position="top"
        :rules="userRule"
        :model="dialogInfo"
        ref="userFormDialog"
        @submit.native.prevent
      >
        <el-form-item prop="username" label="账号名称">
          <el-input v-model.trim="dialogInfo.username"></el-input>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item prop="nickname" label="昵称">
              <el-input v-model.trim="dialogInfo.nickname"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="admin" label="是否管理员">
              <el-radio-group v-model="dialogInfo.admin">
                <el-radio-button :label="1">是</el-radio-button>
                <el-radio-button :label="0">否</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="enabled" label="账号状态">
              <el-switch
                v-model="dialogInfo.enabled"
                active-color="#67C23A"
                active-text="启用"
                :active-value="1"
                inactive-color="#F56C6C"
                inactive-text="禁用"
                :inactive-value="0"
              ></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="email" label="电子邮箱">
              <el-input v-model.trim="dialogInfo.email"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="phone" label="手机号">
              <el-input v-model.trim="dialogInfo.phone"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item prop="roles" label="用户角色">
          <el-select
            multiple
            filterable
            default-first-option
            value-key="id"
            v-model="dialogInfo.roles"
            style="width: 100%"
          >
            <el-option
              v-for="role in roles"
              :key="role.id"
              :value="role"
              :label="role.name"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button icon="el-icon-close" @click="closeDialog">关 闭</el-button>
        <el-button type="success" @click="saveUser" v-loading="loading" icon="el-icon-check">
          保 存
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import { cloneDeep } from 'lodash';
  import { FormRuleConf } from '@/config';

  const DATA_TMP = {
    admin: 0,
    enabled: 1,
    avatar: '',
    phone: '',
    email: '',
  };

  export default {
    data() {
      return {
        searchOpt: [],

        roles: [],
        loading: false,
        dialogShow: false,
        dialogInfo: cloneDeep(DATA_TMP),
        ...FormRuleConf.User,
      };
    },
    mounted() {
      this.getRoleList();
    },
    methods: {
      /**
       * 获取角色列表
       */
      getRoleList() {
        this.$service
          .SysRoleList({
            size: 1000,
          })
          .then((res) => [(this.roles = res.rows)]);
      },
      /**
       * 切换用户状态
       */
      switchEnabled(row) {
        const user = cloneDeep(row);
        this.$confirm(
          `此操作将 "${user.enabled == 1 ? '禁用' : '启用'}" ${user.nickname},确认继续?`,
          '提示',
          {
            type: 'warning',
          },
        )
          .then(() => {
            user.enabled = Number(!user.enabled);
            this.$service
              .SysUserSave(user, {
                ...JSON_HEADER,
              })
              .then(() => {
                this.$refs.userList.getList();
                this.$message.success('用户状态修改成功');
              });
          })
          .catch((err) => {
            user.enabled = row.enabled;
          });
      },

      /**
       * 保存用户
       */
      saveUser() {
        this.$refs.userFormDialog.validate((valid) => {
          if (valid && !this.loading) {
            this.loading = true;
            this.$service
              .SysUserSave(
                {
                  ...this.dialogInfo,
                  avatar: '',
                },
                {
                  ...JSON_HEADER,
                },
              )
              .then((res) => {
                this.$message.success('操作成功');
                this.$refs.userList.getList();
                this.closeDialog();
              })
              .finally(() => [(this.loading = false)]);
          }
        });
      },
      /**
       * 修改用户
       */
      check(row) {
        this.dialogShow = true;
        this.dialogInfo = cloneDeep(row);
      },
      /**
       * 删除用户
       */
      del(row) {
        if (this.loading) return;

        this.loading = true;
        this.$confirm(`确认删除用户 ${row.username} 吗?`, '注意')
          .then(() => {
            return this.$service.SysUserDel({
              id: row.id,
            });
          })
          .then(() => {
            this.$message.success('操作成功');
            this.$refs.userList.getList();
          })
          .finally(() => {
            this.loading = false;
          });
      },
      /**
       * 关闭弹窗
       */
      closeDialog() {
        this.dialogShow = false;
        this.dialogInfo = cloneDeep(DATA_TMP);
      },
    },
  };
</script>

<style lang="less" scoped>
  .system-user {
  }
</style>
